from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from create.models import Create
from .models import Interaction

@login_required
def add_comment(request, story_id):
    """
    添加评论视图
    """
    if request.method == 'POST':
        story = get_object_or_404(Create, id=story_id)
        comment_content = request.POST.get('comment', '')
        
        # 创建或更新用户的交互记录
        interaction, created = Interaction.objects.get_or_create(
            user=request.user,
            stories=story.id,
            defaults={
                'comments': comment_content,
            }
        )
        
        if not created:
            # 如果记录已存在，追加新评论
            interaction.comments += f"\n{comment_content}"
            interaction.save()
        
        return JsonResponse({
            'success': True,
            'message': '评论已添加',
            'comment': comment_content
        })

@login_required
def toggle_favorite(request, story_id):
    """
    切换收藏状态视图
    """
    story = get_object_or_404(Create, id=story_id)
    
    # 获取或创建交互记录
    interaction, created = Interaction.objects.get_or_create(
        user=request.user,
        stories=story.id,
        defaults={
            'favorite': True,
            'like': False,
            'comments': '',
        }
    )
    
    if not created:
        # 切换收藏状态
        interaction.favorite = not interaction.favorite
        interaction.save()
    
    status = "已收藏" if interaction.favorite else "已取消收藏"
    return JsonResponse({
        'success': True,
        'message': status,
        'is_favorite': interaction.favorite
    })

@login_required
def toggle_like(request, story_id):
    """
    切换点赞状态视图
    """
    story = get_object_or_404(Create, id=story_id)
    
    # 获取或创建交互记录
    interaction, created = Interaction.objects.get_or_create(
        user=request.user,
        stories=story.id,
        defaults={
            'favorite': False,
            'like': True,
            'comments': '',
        }
    )
    
    if not created:
        # 切换点赞状态
        interaction.like = not interaction.like
        interaction.save()
    
    status = "已点赞" if interaction.like else "已取消点赞"
    return JsonResponse({
        'success': True,
        'message': status,
        'is_liked': interaction.like
    })